<template>
  <div class="drag-container">
    <transition-group
      name="list"
      tag="ul"
      class="list-container"
    >
      <li
        v-for="(item, index) in items"
        :key="item.id"
        draggable="true"
        @dragstart="onDragStart(index)"
        @dragover.prevent
        @dragenter.prevent="onDragEnter(index)"
        @dragend="onDragEnd"
        class="list-item"
      >
        {{ item.name }}
      </li>
    </transition-group>
  </div>
</template>

<script setup>
import { ref } from "vue";

// 数据和拖拽状态
const items = ref([
  { id: 1, name: "Item 1" },
  { id: 2, name: "Item 2" },
  { id: 3, name: "Item 3" },
  { id: 4, name: "Item 4" },
  { id: 5, name: "Item 5" },
]);

const dragIndex = ref(null);

// 拖拽事件处理函数
const onDragStart = (index) => {
  dragIndex.value = index;
};

const onDragEnter = (index) => {
  if (index === dragIndex.value) return;

  // 交换拖拽项和目标项的位置
  const newItems = [...items.value];
  const draggedItem = newItems[dragIndex.value];
  newItems.splice(dragIndex.value, 1);
  newItems.splice(index, 0, draggedItem);
  items.value = newItems;

  // 更新拖拽索引
  dragIndex.value = index;
};

const onDragEnd = () => {
  dragIndex.value = null;
};
</script>

<style scoped>
.drag-container {
  max-width: 400px;
  margin: 0 auto;
}

.list-container {
  list-style: none;
  padding: 0;
  margin: 0;
}

.list-item {
  padding: 10px 15px;
  margin: 5px 0;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: grab;
  transition: transform 0.3s, opacity 0.3s;
}

.list-item:active {
  cursor: grabbing;
}

.list-enter-active,
.list-leave-active {
  transition: transform 0.3s, opacity 0.3s;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
}
</style>